package com.pyb.config;

import com.pyb.exception.CustomBusinessException;
import com.pyb.pojo.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(CustomBusinessException.class)
    public ResponseEntity<ErrorResponse> handleCustomBusinessException(CustomBusinessException ex) {
        ErrorResponse error = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {
        // 日志记录
        ex.printStackTrace(); // 在生产环境中应该使用日志框架而不是printStackTrace

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMessage", "系统发生错误：" + ex.getMessage());
        modelAndView.setViewName("error"); // 假设有一个名为"error.jsp"的错误页面
        return modelAndView;
    }
}

